from openpyxl import Workbook, load_workbook
import time
import re
import os
from tqdm import tqdm


# 处理changgelog
class HandleChangeLog:
    def __init__(self, file1, file2, file3):
        self.test_department_file = file1
        self.inside_department_file = file2
        self.change_log = file3
        self.repeat_ids = []
        self.need_add = []
        self.write_datas = []
        try:
            os.mkdir("tmp_datas")
        except:
            pass

    def removeLine(self, line):
        remove_words = ["urgency", "commit", "* task", "LP: #", "Task#", "任务号：", "需求号：","patch:"]
        for word in remove_words:
            if line.find(word) > -1:
                return False
        return True

    def write_excel(self):
        wb = Workbook()
        ws = wb.active
        title = ['bug号', '分支', '所属模块', '严重程度', 'bug标题']
        self.write_datas.insert(0, title)
        for index, value in enumerate(self.write_datas):
            for index2, value2 in enumerate(value):
                ws.cell(index + 1, index2 + 1, value=value2)
        wb.save("tmp_datas/禅道-changelog合并数据.xlsx")
        wb.close()

    def handel_change_log(self):
        """
        处理changgelog文件，将四个架构下的changelog汇总去重
        :return: changlog数据
        """
        wb = load_workbook(self.change_log)
        tmp_datas = []
        x86_sheet = wb["x86"]
        arm_sheet = wb["arm"]
        mips_sheet = wb["mips"]
        loongarch_sheet = wb["loongarch"]
        x86_max_line = x86_sheet.max_row
        arm_max_line = arm_sheet.max_row
        mips_max_line = mips_sheet.max_row
        loongarch_max_line = loongarch_sheet.max_row
        print("获取x86 sheet所有数据...")
        for i in range(x86_max_line):
            tmp_datas.append(x86_sheet.cell(i + 2, 4).value)
        print("获取arm sheet所有数据...")
        for i in range(arm_max_line - 1):
            tmp_datas.append(arm_sheet.cell(i + 2, 4).value)
        print("获取mips sheet所有数据...")
        for i in range(mips_max_line - 1):
            tmp_datas.append(mips_sheet.cell(i + 2, 4).value)
        print("获取loongarch sheet所有数据...")
        for i in range(loongarch_max_line - 1):
            tmp_datas.append(loongarch_sheet.cell(i + 2, 4).value)
        print("数据获取成功，数据去重成功！")
        return list(set(tmp_datas))

    def get_test_data(self):
        """
        此方法为将两个测试部门的数据相加
        :param file:
        :return:  测试部和内测之和数据,一个列表包含多个小列表数据
        """
        all_datas = []
        wb_test = load_workbook(self.test_department_file)  # 测试部文件
        wb_inside = load_workbook(self.inside_department_file)  # 内测文件
        test_sheet = wb_test["Bug"]
        inside_sheet = wb_inside["Bug"]
        test_sheet_maxLine = test_sheet.max_row
        inside_sheet_maxLine = inside_sheet.max_row
        print("正在获取文件一所有数据....")
        for i in range(test_sheet_maxLine):  # 获取测试部文件所有数据
            tmp_data = []
            bug_id = test_sheet.cell(i + 2, 1).value
            branch = test_sheet.cell(i + 2, 3).value
            modular = test_sheet.cell(i + 2, 4).value
            Severity = test_sheet.cell(i + 2, 10).value
            bug_title = test_sheet.cell(i + 2, 8).value
            tmp_data.append(bug_id)
            tmp_data.append(branch)
            tmp_data.append(modular)
            tmp_data.append(Severity)
            tmp_data.append(bug_title)
            all_datas.append(tmp_data)
        print("正在获取文件二所有数据....")
        for i in range(inside_sheet_maxLine):  # 获取内测文件所有数据
            tmp_data = []
            bug_id = inside_sheet.cell(i + 2, 1).value
            branch = inside_sheet.cell(i + 2, 3).value
            modular = inside_sheet.cell(i + 2, 4).value
            Severity = inside_sheet.cell(i + 2, 10).value  # 严重程度
            bug_title = inside_sheet.cell(i + 2, 8).value
            tmp_data.append(bug_id)
            tmp_data.append(branch)
            tmp_data.append(modular)
            tmp_data.append(Severity)
            tmp_data.append(bug_title)
            all_datas.append(tmp_data)
        bug_ids = [i[0] for i in all_datas]
        return bug_ids, all_datas

    def handel_log(self, log, ids):
        if log == None or log.find('urgency=low') > -1:
            return ""
        result = log.split('\n')
        for i in result:
            if self.removeLine(i) == False:
                continue
            log_bug_id = re.findall('\d{6}', i)
            if len(log_bug_id) > 0:
                pass
            else:
                log_bug_id = re.findall('\d{5}', i)
            if len(log_bug_id) > 0:
                for j in log_bug_id:
                    if int(j) in ids:
                        self.repeat_ids.append(int(j))
                    else:
                        tmp_datas = []
                        tmp_datas.append(int(j))
                        tmp_datas.append(i)
                        self.need_add.append(tmp_datas)

    def main(self):
        change_log = self.handel_change_log()  # 获取changelog所有内容
        bug_ids, all_datas = self.get_test_data()  # 获取测试所有数据
        for log in change_log:
            self.handel_log(log, bug_ids)
        for data in all_datas:
            if data[0] == None:
                continue
            self.write_datas.append(data)
        self.write_datas = self.write_datas + self.need_add
        self.write_excel()
        print("*" * 60)
        print("禅道与changelog比对数据：")
        print("重复的bug数：", len(self.repeat_ids))
        print("追加的bug数:", len(self.need_add))
        print("禅道中的bug总数：", len(all_datas))
        print("changelog中bug数：", len(self.need_add) + len(self.repeat_ids))
        print("最终文件bug数：", len(self.write_datas))
        print("*" * 60)


if __name__ == '__main__':
    import sys

    test_file = sys.argv[1]
    neice_file = sys.argv[2]
    chandao_file = sys.argv[3]
    print("读入文件：" + test_file + " " + neice_file + " " + chandao_file)
    # HandleChangeLog = HandleChangeLog('测试部.xlsx', "内测.xlsx", 'V10-SP1-RC8-20210820-2 daily 版本内部提测（1014).xlsx')
    HandleChangeLog = HandleChangeLog(test_file, neice_file, chandao_file)
    HandleChangeLog.main()
